package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.RecZmPaperInsideManagement;
import com.ruoyi.system.domain.RecZmPaperManagementD;
import com.ruoyi.system.mapper.RecZmPaperManagementDMapper;
import com.ruoyi.system.service.IRecZmPaperManagementDService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 专门档案  独立的Service业务层处理
 *
 * @author yzf
 * @date 2022-06-03
 */
@Service
public class RecZmPaperManagementDServiceImpl implements IRecZmPaperManagementDService {
    @Autowired
    protected Validator validator;
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RecZmPaperManagementDMapper recZmPaperManagementDMapper;
    @Autowired
    private RedisCache redisCache;

    /***
     * 導出
     * @param archivesId
     * @return
     */
    @Override
    public File selectRecordFileExport(String archivesId) {

        RecZmPaperManagementD recZd = recZmPaperManagementDMapper.selectRecZmPaperManagementDById(archivesId);
        if (ObjectUtil.isNotEmpty(recZd)) {
            List<File> files = CollUtil.newArrayList();
            File f = null;
            String[] filepathArr = null;
            String[] imagespathArr = null;
            //文件存储路径
            String filePath = recZd.getObjStr11();
            if (StrUtil.isNotEmpty(filePath)) {
                filepathArr = filePath.split(",");
                for (String s : filepathArr) {
                    filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                    f = new File(filePath);
                    files.add(f);
                    //   System.out.println(filePath);
                }
            }
            //图片存储路径
            String imgpath = recZd.getObjStr12();
            if (StrUtil.isNotEmpty(imgpath)) {
                imagespathArr = imgpath.split(",");
                for (String s : imagespathArr) {
                    filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                    f = new File(filePath);
                    files.add(f);
                }
            }
            List<Map<String, Object>> excellist = CollUtil.newArrayList();

            //表格
           /* File excelFile = HutoolExcelUtiles.RecordFileExport(JSONArray.parseArray(JSONObject.toJSONString(list)));
            files.add(excelFile);*/
            //生成zip
            String zipPath = RuoYiConfig.getZipPath() + archivesId + "_案卷包" + IdUtil.getSnowflake().nextIdStr() + ".zip";
            File[] zipfiles = ArrayUtil.toArray(files, File.class);

            File file = ZipUtil.zip(FileUtil.file(zipPath), false, zipfiles);
            //   System.out.println(fres.getAbsoluteFile());
            return file;
        }
        return null;
    }

    @Override
    @Transactional
    public String importFile(List<RecZmPaperManagementD> fileList, String operName) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (CollUtil.isEmpty(fileList)) {
            throw new ServiceException("导入文件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecZmPaperManagementD file : fileList) {
            try {
                BeanValidators.validateWithException(validator, file);
                file.setCreateBy(operName);
                this.insertRecZmPaperManagementD(file);
                successNum++;
                successMsg.append("<br/>" + successNum + "、文件 " + file.getFileTitle() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、文件 " + file.getFileTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询专门档案  独立的
     *
     * @param id 专门档案  独立的主键
     * @return 专门档案  独立的
     */
    @Override
    public RecZmPaperManagementD selectRecZmPaperManagementDById(String id) {
        return recZmPaperManagementDMapper.selectRecZmPaperManagementDById(id);
    }

    @Override
    public List<Map<String, Object>> selectlistByName(RecZmPaperManagementD recZmPaperManagementD) {
        return recZmPaperManagementDMapper.selectlistByName(recZmPaperManagementD);
    }

    /**
     * 查询专门档案  独立的列表
     *
     * @param recZmPaperManagementD 专门档案  独立的
     * @return 专门档案  独立的
     */
    @Override
    public List<RecZmPaperManagementD> selectRecZmPaperManagementDList(RecZmPaperManagementD recZmPaperManagementD) {
        return recZmPaperManagementDMapper.selectRecZmPaperManagementDList(recZmPaperManagementD);
    }

    /**
     * 新增专门档案  独立的
     *
     * @param recZmPaperManagementD 专门档案  独立的
     * @return 结果
     */
    @Override
    public int insertRecZmPaperManagementD(RecZmPaperManagementD recZmPaperManagementD) {
        recZmPaperManagementD.setFileNumber(getFileNumber(recZmPaperManagementD));
        recZmPaperManagementD.setCreateTime(DateUtils.getNowDate());
        recZmPaperManagementD.setCreateBy(SecurityUtils.getUsername());
        return recZmPaperManagementDMapper.insertRecZmPaperManagementD(recZmPaperManagementD);
    }

    private String getFileNumber(RecZmPaperManagementD recZmPaperManagementD) {
        //档案号生成   全宗号-年度-件号
        //全宗号
        String fullAncestor = recZmPaperManagementD.getFullAncestor();
        if (StrUtil.isEmpty(fullAncestor)) {
            throw new GlobalException("全宗号不能空,请按规则填写");
        }
        //年度
        String year = recZmPaperManagementD.getYear();
        if (StrUtil.isEmpty(year)) {
            throw  new GlobalException("年度不能空,请按规则填写");
        }
        //件号
        String partNumber = recZmPaperManagementD.getPartNumber();
        if (StrUtil.isEmpty(partNumber)) {
            throw  new GlobalException("件号不能空,请按规则填写");
        }

        StringBuilder stb = new StringBuilder();
        stb.append(fullAncestor).append("-");
        stb.append(year).append("-");
        stb.append(partNumber);
        return stb.toString();
    }

    /**
     * 修改专门档案  独立的
     *
     * @param recZmPaperManagementD 专门档案  独立的
     * @return 结果
     */
    @Override
    public int updateRecZmPaperManagementD(RecZmPaperManagementD recZmPaperManagementD) {
        recZmPaperManagementD.setUpdateTime(DateUtils.getNowDate());
        recZmPaperManagementD.setUpdateBy(SecurityUtils.getUsername());
        return recZmPaperManagementDMapper.updateRecZmPaperManagementD(recZmPaperManagementD);
    }

    /**
     * 批量删除专门档案  独立的
     *
     * @param ids 需要删除的专门档案  独立的主键
     * @return 结果
     */
    @Override
    public int deleteRecZmPaperManagementDByIds(String[] ids) {
        return recZmPaperManagementDMapper.deleteRecZmPaperManagementDByIds(ids);
    }

    /**
     * 删除专门档案  独立的信息
     *
     * @param id 专门档案  独立的主键
     * @return 结果
     */
    @Override
    public int deleteRecZmPaperManagementDById(String id) {
        return recZmPaperManagementDMapper.deleteRecZmPaperManagementDById(id);
    }

    /**
     * 批量文件上传 独立文件
     *
     * @param
     * @return 结果
     */
    @Override
    public int upLoadMultFile(RecZmPaperManagementD recZmPaperManagementD) {
        int res = 0;
        String[] strs = recZmPaperManagementD.getObjStr11().split(",");
        try {
            for(int i=0; i<strs.length; i++){
                System.out.println(strs[i]);
                // 截取最后一次出现.号和最后一个出现-号的字符。比如xxx-001.pdf,截取的是001
                String num = strs[i].substring(strs[i].lastIndexOf("-")+1, strs[i].lastIndexOf("."));
                res = res + mult(num, strs[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private int mult(String num, String path){
        int res = 0;
        RecZmPaperManagementD recZmPaperManagementD = recZmPaperManagementDMapper.getMultBy(num);
        if(recZmPaperManagementD != null && StrUtil.isNotEmpty(recZmPaperManagementD.getObjStr11())){
            String paths = recZmPaperManagementD.getObjStr11() + "," + path;
            recZmPaperManagementD.setObjStr11(paths);
            res = recZmPaperManagementDMapper.updateRecZmPaperManagementD(recZmPaperManagementD);
        }else if(recZmPaperManagementD != null && StrUtil.isEmpty(recZmPaperManagementD.getObjStr11())){
            recZmPaperManagementD.setObjStr11(path);
            res = recZmPaperManagementDMapper.updateRecZmPaperManagementD(recZmPaperManagementD);
        }
        return res;
    }

    @Override
    @Transactional
    public int updateArchivesApplyByIds(String[] Ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : Ids) {
            RecZmPaperManagementD recordArchives = new RecZmPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("1"); //申请状态字段，1：申请
            RecZmPaperManagementD recordArchivesOld = this.selectRecZmPaperManagementDById(id);
            if ("0".equals(recordArchivesOld.getObjStr1()) || "3".equals(recordArchivesOld.getObjStr1())) { // 未申请或拒绝状态，可申请
                int res = this.updateRecZmPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作未申请和审批拒绝的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesApprove(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecZmPaperManagementD recordArchives = new RecZmPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("2"); //申请状态字段,2：通过
            RecZmPaperManagementD recordArchivesOld = this.selectRecZmPaperManagementDById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecZmPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesReject(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecZmPaperManagementD recordArchives = new RecZmPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("3"); //申请状态字段，3：拒绝
            RecZmPaperManagementD recordArchivesOld = this.selectRecZmPaperManagementDById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecZmPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

}
